package com.tongqin.distributed;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @author yuantongqin
 * @date 2018/7/9 下午3:53
 * <p>
 * 处理请求的参数
 */
public class ProcessorHandler implements Runnable {


    private Socket socket;
    private Object server;

    public ProcessorHandler(Socket socket, Object server) {
        this.socket = socket;
        this.server = server;
    }

    @Override
    public void run() {
        //拿到客户端请求的请求
        try {
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            RpcRequest request = (RpcRequest) inputStream.readObject();
            Object result = getServer(request);
            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(result);
            outputStream.flush();
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 根据客户端请求的方法名以及参数
     * 反射调用本地提供的实例方法
     */

    public Object getServer(RpcRequest request) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object[] params = request.getParams();
        Class[] types = new Class[params.length];
        for (int i=0;i<params.length;i++){
            types[i] = params[i].getClass();
        }
        String methodName = request.getMethodName();
        Method method = server.getClass().getMethod(methodName, types);
        return method.invoke(server, params);

    }
}
